<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\common\library\wechat\WxSubMsg;
use app\common\model\Wxapp as WxappModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\common\model\UserBehaviorLog;
/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 获取模版消息
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function moban()
    {
        $wxappId = "10001";
        // 获取小程序配置
        $wxConfig = WxappModel::getWxappCache($wxappId);
        // 请求微信api执行发送
        $WxSubMsg = new WxSubMsg($wxConfig['app_id'], $wxConfig['app_secret']);
        return $WxSubMsg->getTemplateList();
    }
    /**
     * 设为默认
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function jiuzheng_moren($jiuzhen_id)
    {
        // 查询当前就诊人，获取 user_id
        $currentJiuzhen = DB('user_jiuzhen')->where('jiuzhen_id', $jiuzhen_id)->find();

        if (!$currentJiuzhen) {
            return $this->renderError('就诊人信息不存在');
        }

        $userId = $currentJiuzhen['user_id'];

        // 将该用户的所有就诊人 is_mr 字段设置为 0
        DB('user_jiuzhen')
            ->where('user_id', $userId)
            ->update(['is_mr' => 0]);

        // 将当前就诊人的 is_mr 设置为 1
        $result = DB('user_jiuzhen')
            ->where('jiuzhen_id', $jiuzhen_id)
            ->update(['is_mr' => 1]);

        // 检查更新结果并返回响应
        if ($result !== false) {
            return $this->renderSuccess('默认就诊人设置成功');
        } else {
            return $this->renderError('设置默认就诊人失败');
        }
    }
    /**
     * 解绑就诊人
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function jiuzheng_jb($jiuzhen_id)
    {
        if (DB('user_jiuzhen')->where("jiuzhen_id",$jiuzhen_id)->update(['is_del'=>'1'])) {
            return $this->renderSuccess('解绑成功');
        }
        return $this->renderSuccess('解绑成功');
    }
    /**
     * 关注
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function guanzhu($sta, $goods_id)
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        $user_id = $userInfo['user_id'];

        // 判断用户是否已关注该医生
        $exists = DB('user_guanzhu')
            ->where('user_id', $user_id)
            ->where('goods_id', $goods_id)
            ->find();

        if ($sta == 1) {
            // 如果是关注，且未关注过，则新增数据
            if (!$exists) {
                DB('user_guanzhu')->insert([
                    'user_id' => $user_id,
                    'goods_id' => $goods_id,
                ]);
                return $this->renderSuccess('关注成功');
            } else {
                return $this->renderError('已关注该医生');
            }
        } elseif ($sta == 0) {
            // 如果是取消关注，且已关注，则删除数据
            if ($exists) {
                DB('user_guanzhu')
                    ->where('user_id', $user_id)
                    ->where('goods_id', $goods_id)
                    ->delete();
                return $this->renderSuccess('取消关注成功');
            } else {
                return $this->renderError('未关注该医生');
            }
        } else {
            return $this->renderError('无效的操作');
        }
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function xieyi()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        $user_id = $userInfo['user_id'];
        $arr = DB("user_xieyi")->where("user_id",$user_id)->find();
        return $this->renderSuccess($arr);
    }
    public function xieyipost()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        $user_id = $userInfo['user_id'];
        $date['user_id'] = $user_id;
        $date['wxapp_id'] = 10001;
        $date['create_time'] = time();
        $arr = DB("user_xieyi")->insert($date);
        return $this->renderSuccess($arr);
    }
    public function guanzhu_list()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        $user_id = $userInfo['user_id'];
        $domain = request()->domain(); // 获取当前域名
        // 查询用户关注的商品信息
        $list = DB('user_guanzhu')
        ->alias('g')
        ->field([
            'g.id',
            'g.goods_id',
            'goods.goods_name',
            'goods.content as con',
            '(goods.sales_initial + goods.sales_actual) as goods_sales',
            'sku.goods_no',
            'goods.selling_point',
            "CONCAT('$domain/uploads/', file.file_name) as image_url" // 拼接完整图片路径
        ])
        ->join('user', 'g.user_id = user.user_id') // 关联 user 表
        ->join('goods', 'g.goods_id = goods.goods_id') // 关联 goods 表
        ->join('goods_sku sku', 'goods.goods_id = sku.goods_id') // 关联 goods_sku 表
        ->join('goods_image img', 'goods.goods_id = img.goods_id') // 关联 goods_img 表
        ->join('upload_file file', 'img.image_id = file.file_id') // 关联 upload_file 表
        ->where('g.user_id', '=', $user_id) // 筛选当前用户的关注列表
        ->where('goods.is_delete', '=', 0) // 过滤已删除的商品
        ->order(['g.id' => 'desc']) // 按关注时间降序排列
        ->select();

        return $this->renderSuccess($list);
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function addjiuzheng()
    {
        $input = input();
        // 当前用户信息
        $userInfo = $this->getUser();
        
        if (!$userInfo) {
            $this->throwError('没有找到用户信息', -1);
        }

        // 验证身份证号码
        // if (!$this->validateIdCard($input['zhengjiannb'])) {
        //     // return $this->renderError('身份证号码不正确');
        // }
        
        // 验证身份证号码与生日是否匹配
        // if (!$this->validateIdCardWithBirthday($input['zhengjiannb'], $input['shengri'])) {
        //     // return $this->renderError('身份证号码或生日不匹配');
        // }
        // 准备数据
        $data['user_id'] = $userInfo['user_id'];
        $data['guanxi'] = $input['guanxi'];
        $data['name'] = $input['name'];
        $data['zhengjian'] = $input['zhengjian'];
        $data['zhengjiannb'] = "";
        $data['sex'] = $input['sex'];
        $data['minzu'] = '';
        $data['shengri'] = $input['shengri'];
        $data['phone'] = $input['phone'];
        $data['create_time'] = time();
        
        // return 111;die;
        // 判断是否已有就诊人
        $existing = DB("user_jiuzhen")->where('user_id', $userInfo['user_id'])->where("is_del","0")->count();
        
        $data['is_mr'] = ($existing > 0) ? 0 : 1; // 如果已有就诊人，则设置为 0；否则设置为 1
        // 插入数据
        if (DB("user_jiuzhen")->insert($data)) {
            return $this->renderSuccess();
        } else {
            return $this->renderError('添加失败');
        }
    }
    public function validateIdCardWithBirthday($idCard, $birthday)
    {
        // 18位身份证号码正则表达式
        $pattern = '/^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i';
        if (!preg_match($pattern, $idCard)) {
            return false; // 格式不正确
        }

        // 身份证中的生日部分（第7到14位）
        $idCardBirthday = substr($idCard, 6, 8); // 格式：YYYYMMDD
        $idCardBirthdayFormatted = substr($idCardBirthday, 0, 4) . '-' . substr($idCardBirthday, 4, 2) . '-' . substr($idCardBirthday, 6, 2);

        // 检查身份证中的生日是否与传入的生日匹配
        if ($idCardBirthdayFormatted !== $birthday) {
            return false; // 生日不匹配
        }

        // 身份证号码中的前17位和校验位
        $base = substr($idCard, 0, 17);
        $checkDigit = strtoupper(substr($idCard, 17, 1)); // 校验位（可能是数字或 'X'）

        // 权重因子
        $weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // 校验码
        $checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

        // 计算校验和
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            $sum += $base[$i] * $weightFactors[$i];
        }

        // 计算校验码
        $calculatedCheckDigit = $checkCode[$sum % 11];

        // 验证校验码
        return $calculatedCheckDigit === $checkDigit;
    }
    public function validateIdCard($idCard)
    {
        // 18位身份证号码正则表达式
        $pattern = '/^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i';
        if (!preg_match($pattern, $idCard)) {
            return false; // 格式不正确
        }

        // 身份证号码中的前17位和校验位
        $base = substr($idCard, 0, 17);
        $checkDigit = strtoupper(substr($idCard, 17, 1)); // 校验位（可能是数字或 'X'）

        // 权重因子
        $weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // 校验码
        $checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

        // 计算校验和
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            $sum += $base[$i] * $weightFactors[$i];
        }

        // 计算校验码
        $calculatedCheckDigit = $checkCode[$sum % 11];

        // 验证校验码
        return $calculatedCheckDigit === $checkDigit;
    }
    /**
     * 就诊人详情
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function jiuzheng_info($jiuzhen_id)
    {
        $arr = DB("user_jiuzhen")->where("jiuzhen_id",$jiuzhen_id)->find();
        return $this->renderSuccess(compact('arr'));
    }
    /**
     * 就诊人列表
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function listjiuzheng()
    {
        $userInfo = $this->getUser();
        if (!$userInfo) {
            $this->throwError('没有找到用户信息', -1);
        }
        
        // 获取列表
        $list = DB("user_jiuzhen")
            ->where("user_id", $userInfo['user_id'])
            ->where("is_del", "0")
            ->order("is_mr desc")
            ->select()
            ->toArray(); // 转换为数组

        // 格式化数据
        foreach ($list as &$item) {
            // 处理 name 字段，前面用 * 替换，保留最后一个字符
            if (!empty($item['name'])) {
                $lastChar = mb_substr($item['name'], -1, 1, 'UTF-8'); // 获取最后一个字符
                $item['name'] = str_repeat('*', mb_strlen($item['name'], 'UTF-8') - 1) . $lastChar; // 用 * 替换前面的字符
            }
            
            // 处理身份证号，显示前4位和后4位，中间用*号隐藏
            if (!empty($item['zhengjiannb'])) {
                $item['zhengjiannb'] = substr($item['zhengjiannb'], 0, 4) . '****' . substr($item['zhengjiannb'], -4);
            }
        }
        unset($item); // 解除引用
        return $this->renderSuccess(compact('list'));
    }
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $postData = $this->request->post();

        // ==== 写入日志 ====
        $logDir = __DIR__ . '/../../../runtime/user_login_log';  // 你也可以改为绝对路径  // 日志目录
        
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);  // 若不存在则创建
        }

        $logFile = $logDir . '/' . date('Y-m-d') . '.log';  // 每天一个文件
        $logText = sprintf(
            "[%s] IP: %s\n%s\n\n",
            date('Y-m-d H:i:s'),
            $this->request->ip(),
            json_encode($postData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
        );

        file_put_contents($logFile, $logText, FILE_APPEND);

        // ==== 正常登录逻辑 ====
        $model = new UserModel;
        return $this->renderSuccess([
            'user_id' => $model->login($this->request->post()),
            'token' => $model->getToken()
        ]);
    }

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        return $this->renderSuccess(compact('userInfo'));
    }
    // 新增用户改昵称和头像
    public function updatenickname()
    {
        $userInfo = $this->getUser();
        $user_id = $userInfo['user_id'];
        $arr['nickName'] = input()['nickName'];
        
        if (isset(input()['avatarUrl'])) {
            $arr['avatarUrl'] = input()['avatarUrl'];
        }
        
        $model = new UserModel;
        $model->where("user_id", $user_id)->update($arr);
        return $this->renderSuccess([],"修改成功");
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function phone()
    {
        $userInfo = $this->getUser();
        $user_id = $userInfo['user_id'];
        $arr['phone'] = input()['phone'];
        $model = new UserModel;
        $model->where("user_id", $user_id)->update($arr);
        return $this->renderSuccess([],"修改成功");
    }
    /**
     * 记录用户行为
     */
    // CREATE TABLE `user_behavior_log` (
    //   `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    //   `user_id` INT NOT NULL COMMENT '用户ID',
    //   `action` VARCHAR(255) NOT NULL COMMENT '行为描述（如：点击了XXX）',
    //   `url` VARCHAR(500) DEFAULT '' COMMENT '访问页面地址',
    //   `device` VARCHAR(255) DEFAULT '' COMMENT '设备信息（如：iPhone/Chrome）',
    //   `ip` VARCHAR(45) DEFAULT '' COMMENT 'IP地址',
    //   `extra` TEXT COMMENT '附加数据（JSON结构）',
    //   `create_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '记录时间'
    // ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户行为轨迹日志';
    public function track()
    {
        $data = $this->request->post();
        // dump($data);die;
        // 获取当前登录用户ID
        $user_id = $this->getUser() ? $this->getUser()['user_id'] : 0;
        $model = new UserBehaviorLog;
        $model->create([
            'user_id' => $user_id,
            'fromroute'  => $data['fromRoute'] ?? '',
            'route'  => $data['route'] ?? '',
            'action'     => $data['scene'] ?? '',
            'extra'   => json_encode($data['extra'] ?? [], JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s', $data['timestamp'] / 1000)

        ]);

        return $this->renderSuccess('记录成功');
    }
}
